package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.job.TaskException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

private static final String REQUEST_URL= "https://api.weixin.qq.com/sns/jscode2session";
private static final String TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token";
private static final String PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;
    @Override
    public String getOpenid(String code) {
        Map<String,Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("secret",secret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpUtil.get(REQUEST_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(json);
//        if(jsonObject.get("errcode")!=null){
//            throw new RuntimeException(jsonObject.getStr("errmsg"));
//        }
        System.out.println("jsonObject = " + jsonObject);
        return jsonObject.getStr("openid");
    }

    @Override
    public String getPhone(String detailCode) {
        String token = getToken();
        String url = PHONE_URL+token;
        Map<String,Object> map = new HashMap<>();
        map.put("code",detailCode);
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(map));
        JSONObject jsonObject = JSONUtil.parseObj(result);
//        if(jsonObject.get("errcode")!=null){
//            throw new RuntimeException(jsonObject.getStr("errmsg"));
//        }
//        Object phoneNumber = jsonObject.getJSONObject("phone_info").get("phoneNumber");
        String phone = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
//        String phone = phoneNumber.toString();
        return phone;
    }

    private String getToken() {
        Map<String,Object> map = new HashMap<>();
        map.put("grant_type","client_credential");
        map.put("appid",appid);
        map.put("secret",secret);
        String result = HttpUtil.get(TOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(jsonObject.get("errcode")!=null){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }
}
